<template>
  <Panel :title="title" class="Panel">
    <el-container>
      <el-aside class="aside-content">
        <span>
          <el-button  type="text"
                      size="mini"
                      @click="() => addChapter()"
                      icon="el-icon-circle-plus-outline">
            添加章
          </el-button>
        </span>
        <el-tree :data="data"
                  node-key="id"
                  default-expand-all
                  ref="tree"
                  :expand-on-click-node="false"
                  :highlight-current="true"
                  @current-change="handleCurrentClick">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <el-tooltip content="添加节" placement="top">
                <el-button 
                  type="text"
                  size="mini"
                  @click="() => addSection(data)"
                  v-if="data.level == 1">
                  <i class="el-icon-tickets"></i>
                </el-button>
              </el-tooltip>
              <el-button
                type="text"
                size="mini"
                @click="() => edit(data)">
                <i class="el-icon-edit"></i>
              </el-button>
              <el-button
                type="text"
                size="mini"
                @click="() => deleteNode(node, data)">
                <i class="el-icon-delete"></i>
              </el-button>
            </span>
          </span>
        </el-tree>
      </el-aside>
      <el-main class="main_resources"> 
        <p class="addResourceNotice" v-if="currentNode.level != 2">请先添加课程章和节，然后选中某一个节添加课程资源</p>
        <div class="videoExample" v-if="currentNode.level === 2"> 
          <creation :chapterData="section" :key="time" />
        </div>
      </el-main>
    </el-container>
  </Panel>
</template>

<script>
  import api from '../../api.js'
  import creation from './CourseResourceCreation/Creation.vue'
  export default {
    components: { creation },
    data () {
      return {
        time: new Date().getTime(),
        data: [],
        title: '课程资源编排',
        courseResource: [],
        currentNode: {},
        // 传给Creation的节的资源数据
        section: {
          id: 0,
          resources: []
        }
      }
    },
    mounted () {
      // 获取课程目录章信息
      api.getCourseChapter(this.$route.params.courseId).then(res => {
        let tmp = res.data.data
        for (var x = 0; x < tmp.length; x++) {
          let newObject = {
            id: tmp[x].id,
            label: tmp[x].title,
            level: 1,
            children: []
          }
          // 获取节信息
          api.getCourseSection(this.$route.params.courseId, tmp[x].id).then(res => {
            let tmpSec = res.data.data
            for (var z = 0; z < tmpSec.length; z++) {
              if (newObject.id === tmpSec[z].chapter.id) {
                let newSec = {
                  id: tmpSec[z].id,
                  label: tmpSec[z].title,
                  level: 2,
                  resources: tmpSec[z].resources[0]
                }
                newObject.children.push(newSec)
              }
            }
          })
          this.data.push(newObject)
        }
      })
      // 获取该课程的所有资源
      api['getCourseResourceInfo'](this.$route.params.courseId).then(res => {
        this.courseResource = res.data.data.results
      })
    },
    methods: {
      addChapter () {
        // 在所有章的最后添加一个章
        this.$prompt('请输入章标题', '添加章', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({ value }) => {
          if (value) {
            let newObjId = this.data.length + 1
            let newObj = { id: newObjId, label: value, level: 1, children: [] }
            this.data.push(newObj)
            // 发送数据到后端
            let passData = { 'course': this.$route.params.courseId, 'title': value } // 传送课程编号，章标题
            api['createCourseChapter'](passData).then(res => {
              newObj.id = res.data.data.id
            }).catch((e) => {
            })
          } else {
            this.$message.error('标题不可以为空')
          }
        }).catch((e) => {})
      },

      addSection (data) {
        this.$prompt('请输入节标题', '添加节', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({ value }) => {
          if (value) {
            let newChildId = data.children.length + 1
            const newChild = { id: newChildId, label: value, level: 2, children: [] }
            if (!data.children) {
              this.$set(data, 'children', [])
            }
            data.children.push(newChild)
            // 传递数据到后端
            let passData = {
              'course': this.$route.params.courseId,
              'chapter': data.id,
              'title': value
            } // 传送课程编号，课程目录章编号ID，节标题
            api['createCourseSection'](passData).then(res => {
              newChild.id = res.data.data.id
            }).catch((e) => {
            })
          } else {
            this.$message.error('标题不可以为空')
          }
        }).catch((e) => {})
      },

      edit (data) {
        this.$prompt('请输入新标题', '修改', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: data.label
        }).then(({ value }) => {
          if (value) {
            // 修改
            data.label = value
            // 传递数据到后端
            let passData = {}
            if (data.level === 1) {
              // 修改章
              passData = { 'id': data.id, 'title': value }  // 章编号，修改的值
              api['updateCourseChapter'](passData).then(res => {
              }).catch((e) => {
              })
            } else if (data.level === 2) {
              // 修改节
              passData = { 'id': data.id, 'title': value }  // 节编号，修改的值
              api['updateCourseSection'](passData).then(res => {
              }).catch((e) => {})
            }
          } else {
            this.$message.error('标题不可以为空')
          }
        }).catch(() => {
        })
      },

      // 删除选中的目录
      deleteNode (node, data) {
        this.$confirm('确定删除此目录吗？', '注意', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // then 为确定
          let deleteNodeId = data.id
          const parent = node.parent
          const children = parent.data.children || parent.data
          const index = children.findIndex(d => d.id === data.id)
          children.splice(index, 1)
          // 传递数据到后端删除
          if (data.level === 1) {
            // 删除章
            api.deleteCourseChapter(deleteNodeId).then(res => {
            })
          } else if (data.level === 2) {
            // 删除节
            api.deleteCourseSection(deleteNodeId).then(res => {
            })
          }
        }).catch(() => {
          // catch 为取消
          this.loading = false
        })
      },

      // 查看当前节是否有资源，有显示图片，没有显示添加按钮
      handleCurrentClick (data, node) {
        this.currentNode = node
        this.section.id = this.currentNode.data.id // 传递section id到creation
        if (data.level === 2) {
          // 查看对应节是否有资源
          api['getCatalogResource'](this.currentNode.data.id).then(res => {
            let sectionResource = res.data.data
            // 没有资源显示按钮
            if (sectionResource.length === 0) {
              this.section.resources = []
            } else {
              // 传递资源到creation
              this.section.resources = sectionResource
            }
          })
        } else {
          this.hasSectionResExsit = false
        }
        this.time = new Date().getTime()
      }
    }
  }
 </script>

<style>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .el-tree {
    background: #f9f7f7;
    border-radius:5px;
    margin-right:10px;
  }

  .main_resources {
    /* border: 1px solid lightgrey; */
    border-radius:5px;
  }

  .saveBtn {
    margin-top:20px;
  }

  .videoExample img{
    width: 400px;
    border: 1px solid lightgrey;
  }

  .videoExample{
    margin: 10px 0;
    text-align: center;
  }

  .el-radio {
    display: block;
  }

  .el-radio+.el-radio {
    margin-left: 0;
    margin-top: 10px;
  }

  .addResourceNotice{
    text-align: center;
  }

  .aside-content::-webkit-scrollbar{
    display: none;
  }
  .aside-content{
    width: auto !important; 
    overflow-y: scroll;
    height:73vh;
  }

  .custom-tree-node span:first-child{
    margin-right:3px;
  }
  .el-tree-node>.el-tree-node__children {
    overflow: visible;
  }
  .Panel{
    height:100%;
  }
  .el-tree__empty-block {
    min-height: 200px;
    min-width: 150px;
  }
  .resourceDialog{
    margin-bottom: 20px;
  }
  .el-autocomplete-suggestion{
  width: auto!important;
  }
  .el-input {
    width: 250px;
  }
</style>
